package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.article.config.CacheService;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.HotArticleService;
import com.heima.common.constants.app.ArticleConstants;
import com.heima.feigns.admin.AdminFeign;
import com.heima.model.admin.pojos.AdChannel;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.vos.HotArticleVo;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class HotArticleServiceImpl implements HotArticleService {
    @Autowired
    ApArticleMapper apArticleMapper;
    @Autowired
    CacheService cacheService;
    @Autowired
    AdminFeign adminFeign;
    /**
     * 计算热文章
     */
    @Override
    public void computerHotArticle() {
        //1.查询5天前所有的文章(未下架和删除)
        String time = DateTime.now().minusDays(5).toString("yyyy-MM-dd 00:00:00");
        List<ApArticle> articleList = apArticleMapper.selectList(Wrappers.<ApArticle>lambdaQuery()
                .gt(ApArticle::getPublishTime, time));
        if (articleList==null||articleList.size()==0){
            log.info("****apArticleList is null");
            return;
        }
        //2.计算文章的分值
        List<HotArticleVo> hotArticleVos =computerArticleScore(articleList);
        //3.缓存热点文章
        cacheTagToRedis(hotArticleVos);

    }

    /**
     * 缓存热点文章
     * @param hotArticleVos
     */
    private void cacheTagToRedis(List<HotArticleVo> hotArticleVos) {
        //获得所有频道
        List<AdChannel> allChannels = adminFeign.findAllChannels();
        //缓存对应文章下的热点文章
        allChannels.forEach(adChannel -> {
            List<HotArticleVo> channelHotList = hotArticleVos.stream()
                    .filter(hotArticleVo -> hotArticleVo.getChannelId() == adChannel.getId())
                    .collect(Collectors.toList());
            //对应频道下的文章
            sortAndCache(channelHotList, ArticleConstants.HOT_ARTICLE_FIRST_PAGE + adChannel.getId());
        });
        //缓存推荐下的热点文章
        sortAndCache(hotArticleVos, ArticleConstants.HOT_ARTICLE_FIRST_PAGE + ArticleConstants.DEFAULT_TAG);
    }

    private void sortAndCache(List<HotArticleVo> hotArticleVos, String key) {
        //排序
        hotArticleVos = hotArticleVos.stream()
                .sorted(Comparator.comparing(HotArticleVo::getScore).reversed())
                .limit(30)
                .collect(Collectors.toList());
        //缓存到redis
        cacheService.set(key, JSON.toJSONString(hotArticleVos));
    }

    /**
     * 计算文章分值
     * @param articleList
     * @return
     */
    private List<HotArticleVo> computerArticleScore(List<ApArticle> articleList) {
        ArrayList<HotArticleVo> hotArticleVos = new ArrayList<>();
        for (ApArticle apArticle : articleList) {
            HotArticleVo hotArticleVo = new HotArticleVo();
            BeanUtils.copyProperties(apArticle,hotArticleVo);
            //计算分数
            int score = apArticlecomputeScore(apArticle);
            hotArticleVo.setScore(score);

            hotArticleVos.add(hotArticleVo);
        }
        return hotArticleVos;

    }

    /**
     * 计算分值方法
     * @param apArticle
     * @return
     */
    private int apArticlecomputeScore(ApArticle apArticle) {
        int score = 0;
        //阅读 1
        if (apArticle.getViews() != null) {
            score += apArticle.getViews() * 1;
        }

        //点赞 3
        if (apArticle.getLikes() != null) {
            score += apArticle.getLikes() * 3;
        }

        // 评论 5
        if (apArticle.getComment() != null) {
            score += apArticle.getComment() * 5;
        }
        // 收藏 8
        if (apArticle.getCollection() != null) {
            score += apArticle.getCollection() * 8;
        }

        return score;
    }
}
